package com.esoon.utils;

import android.os.Message;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.os.Handler;
import android.widget.ImageView;

public class UploadImage {
    private static final String TAG = "uploadFile";
    private static final int TIME_OUT = 10 * 10000000; //超时时间
    private static final String CHARSET = "utf-8"; //设置编码
    private static final String BOUNDARY = "FlPm4LpSXsE"; //UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n";
    private static final String PREFIX = "--";
    private static final String LINE_END = "\n\r";
    private static final String CONTENT_TYPE = "multipart/form-data"; //内容类型


    public static void uploadFile1(String fileName, String uploadUrl, Handler handler, String userId, ImageView imageView) {

        try {

            // 换行符
            final String newLine = "\r\n";
            final String boundaryPrefix = "--";
            // 定义数据分隔线
            String BOUNDARY = "========7d4a6d158c9";
            // 服务器的域名
            URL url = new URL(uploadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置为POST情
            conn.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求头参数

            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(conn.getOutputStream());

            // 上传文件
            File file = new File(fileName);
            StringBuilder sb = new StringBuilder();


            Map<String, String> map = new HashMap<>();
            map.put("type", "face_1");
            map.put("seqId", "1");
            map.put("userId", userId);
            map.put("uploadTime", "2019-04-09 13:34:23");


            for (Map.Entry<String, String> entry : map.entrySet()) {
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(newLine);
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + newLine);
                sb.append("Content-Type: text/plain; charset=" + CHARSET + newLine);
                sb.append("Content-Transfer-Encoding: 8bit" + newLine);
                sb.append(newLine);
                sb.append(entry.getValue());
                sb.append(newLine);
            }
            System.out.println(sb.toString());
            out.write(sb.toString().getBytes());
            sb.setLength(0);


            sb.append(boundaryPrefix);
            sb.append(BOUNDARY);
            sb.append(newLine);
            // 文件参数,photo参数名可以随意修改
            sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + fileName
                    + "\"" + newLine);
            sb.append("Content-Type:application/octet-stream");
            // 参数头设置完以后需要两个换行，然后才是参数内容
            sb.append(newLine);
            sb.append(newLine);
            //  out.write(sb1.toString().getBytes());
            System.out.println(sb.toString());
            // 将参数头的数据写入到输出流中
            out.write(sb.toString().getBytes());

            // 数据输入流,用于读取文件数据
            DataInputStream in = new DataInputStream(new FileInputStream(
                    file));
            byte[] bufferOut = new byte[1024];
            int bytes = 0;
            // 每次读1KB数据,并且将文件数据写入到输出流中
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            // 最后添加换行
            out.write(newLine.getBytes());
            in.close();

            // 定义最后数据分隔线，即--加上BOUNDARY再加上--。
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
                    .getBytes();
            // 写上结尾标识
            out.write(end_data);
            out.flush();
            out.close();

            /**
             * 获取响应码 200=成功
             * 当响应成功，获取响应的流
             */
            int res = conn.getResponseCode();
            System.out.println("response code:" + res);
            if (res == 200) {
                String oneLine;
                StringBuffer response = new StringBuffer();
                BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((oneLine = input.readLine()) != null) {
                    response.append(oneLine);
                }

                Message message = new Message();
                message.what = 10;
                message.obj = response.toString();
                handler.sendMessage(message);
                System.out.println(response);

            } else {

            }


        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
    }


}
